package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //商品三级分类的树形结构
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.查询一级分类
        List<CategoryEntity> level1 = entities.stream()
                .filter(categoryEntity ->
                        categoryEntity.getParentCid() == 0)
                //封装子菜单
                .map(category -> {
                    category.setChildren(getChildrens(category, entities));
                    return category;
                })
                //根据sort排序,判空操作
                .sorted((category1, category2) ->
                        (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort()))
                .collect(Collectors.toList());

        return level1;
    }

    //递归封装父子结构
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(category -> {
                    category.setChildren(getChildrens(category, all));
                    return category;
                })
                .sorted((category1, category2) ->
                        (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort()))
                .collect(Collectors.toList());
        return children;
    }

    //删除分类
    @Override
    public void removeCatByIds(Long[] catIds) {
        //todo 删除有关分类的东西
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

}